<script setup lang="ts">
import { commonService } from '@/services/common.service';
import { Message } from '@arco-design/web-vue';
import { ref, watch } from 'vue';


const emit = defineEmits(['update:value'])
const isRecording = ref(false);
const isConvert = ref(false);

let mediaRecorder = null;
const maxTime = 60000; // 最大录音时长 ms
const currDuration = ref(0);  // 已录时长

function startRecording(): void {
  navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
    mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();
    isRecording.value = true;
    // 录音结束时，停止并下载录音文件
    mediaRecorder.addEventListener("dataavailable", function (event) {
      isRecording.value = false;
      const file = new File([event.data], Date.now() + '.mp3', { type: "audio/mp3" });
      onConvert(file);
    });
    onStart();
  }).catch(err => {
    console.error('授权失败', err);
    Message.error('授权失败，请手动打开录音权限');
  })
}
function stopRecording(): void {
  mediaRecorder.stop();
  clearInterval(interval);
  currDuration.value = 0;
}

let interval = null;
function onStart(): void {
  interval = setInterval(() => {
    if (currDuration.value >= maxTime / 1000) {
      Message.warning("单次最长支持" + maxTime / 1000 + '秒');
      stopRecording();
    } else {
      currDuration.value++
    }
  }, 1000)
}

function onConvert(file: File): void {
  isConvert.value = true;
  commonService.vtt(file, (res => {
    isConvert.value = false;
    emit('update:value', res)
  }), () => {
    isConvert.value = false
    Message.error("文本生成失败，请再试一次吧")
  })
}

</script>
<template>
  <div class="vtt">
    <div class="convert" v-if="isConvert">
      <icon-sync size="25" spin />
    </div>
    <div class="" v-else>
      <div class="recording flex" v-if="isRecording">
        <div class="desc flex">{{ currDuration }}/{{ maxTime / 1000 }}s</div>
        <a-tooltip content="结束并开始转文本" mini>
          <icon-record-stop @click="stopRecording" size="25" />
        </a-tooltip>
      </div>
      <icon-voice v-else @click="startRecording" size="25" />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.vtt {
  cursor: pointer;
}

.recording {
  color: rgb(var(--red-5));

  .desc {
    font-size: 12px;
    color: rgb(var(--arcoblue-5));
    margin-right: 4px;
  }
}

.convert {
  color: rgb(var(--arcoblue-5));
}
</style>